package org.chispa.api.parsers;

import java.util.HashMap;
import java.util.Scanner;

public class StateRepository {
	
	private StateRepository(){};
	
	private static HashMap<String,StateRepository>map=new HashMap<String,StateRepository>();
	
	
	public static StateRepository getInstance(){
		String name=Thread.currentThread().getName();
		StateRepository instance=map.get(name);
		if(instance==null)
		{
			instance=new StateRepository();
			map.put(name, instance);
		}
		return instance;
	};
	
	public static enum State{LITERAL,HASH,ENCRYPTION, INITIAL};
	
	private LiteralParserState literal;
	private HashMethodParserState method;
	private EncryptParserState enc;
	private ParserState initial;
	
	public ParserState getInitialState(Scanner scan)
	{
		if(initial==null)
		{
			initial=new InitialParserState(scan);
		}
		return initial;
	}

	protected ParserState getStateFor(State state,ParserState prev)
	{
		if(state.equals(State.LITERAL))
		{
			if(literal==null || !prev.equals(literal.prev))
				literal=new LiteralParserState(prev);
			literal.setBuffer(prev.buffer);
			return literal;
		}
		
		else if(state.equals(State.INITIAL))
		{
			initial.setBuffer(prev.buffer);
			return initial;
		}
		
		else if(state.equals(State.ENCRYPTION))
		{
			if(enc==null || !prev.equals(enc.prev))
				enc=new EncryptParserState(prev);
			enc.setBuffer(prev.buffer);
			return enc;
		}

		if(method==null || !prev.equals(method.prev))
			method=new HashMethodParserState(prev);
		method.setBuffer(prev.buffer);
		return method;

	}

	public void reset() {
		literal=null;
		method=null;
		enc=null;
		initial=null;
		
	}

}
